package com.example.demo.spider;

import cn.hutool.core.thread.ThreadUtil;
import cn.hutool.core.util.ReUtil;
import cn.hutool.core.util.StrUtil;
import org.openqa.selenium.*;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.support.ui.WebDriverWait;
import org.springframework.stereotype.Component;
import us.codecraft.webmagic.Page;
import us.codecraft.webmagic.Site;
import us.codecraft.webmagic.Spider;
import us.codecraft.webmagic.processor.PageProcessor;
import us.codecraft.webmagic.selector.Html;
import us.codecraft.webmagic.selector.Selectable;

import java.util.List;
import java.util.Set;

@Component
public class MailSinaProcessor implements PageProcessor {
    private static final String BASE_URI = "http://81.cn/yw/";
    private static final String DETAIL = ".+pos=\\d+";
    private static final Site SITE = Site.me().setRetryTimes(3).setSleepTime(100);
    private Set<Cookie> cookies;

    @Override
    public void process(Page page) {
        Html html = page.getHtml();
        String base_path = "/html/body/table/tbody/tr[2]/td/table/tbody/tr/td[2]/form";
        if (page.getUrl().regex(DETAIL).match()) {
            String content = html.xpath(base_path + "/table[3]/tbody/tr[3]/td").get()/*.replaceAll("<br>", "\r\n")*/;
            String strDate = ReUtil.get("(面试|面谈)时间：(.+?)<br>", content, 2);
            String addr = ReUtil.get("(面试地址|面试地点)：(.+?)<br>", content, 2);
            page.putField("content", content);
        } else {
            List<Selectable> nodes = html.xpath(base_path + "/table[2]/tbody/tr").nodes();
            for (Selectable node : nodes) {
                String subText = node.xpath("//td[6]/p/a/text()").get();
                String subLink = node.xpath("//td[6]/p/a/@href").get();
                if (StrUtil.isBlank(subText)) continue;
                if (subText.contains("面试邀") || subText.contains("面试通知")) {
                    page.addTargetRequest(subLink);
//                    System.err.println(subText);
                }
            }
            String next = html.xpath(base_path + "/table[1]/tbody/tr[3]/td[2]/span[4]/a/@href").get();
            page.addTargetRequest(next);
        }
    }

    @Override
    public Site getSite() {
        cookies.forEach(cookie -> SITE.addCookie(cookie.getName(), cookie.getValue()));
        SITE.setUserAgent("Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/78.0.3904.108 Safari/537.36");
        return SITE;
    }

    public static void main(String[] args) {
        MailSinaProcessor processor = new MailSinaProcessor();
        processor.login("https://mail.sina.com.cn");
//        Spider.create(processor).addUrl("https://m1.mail.sina.com.cn/classic/index.php").run();
        Spider.create(processor).addUrl("https://m1.mail.sina.com.cn/basic").run();
    }

    public void start() {
        this.login("https://mail.sina.com.cn");
        Spider.create(this).addUrl("https://m1.mail.sina.com.cn/basic/listmail.php?fid=new").run();
    }

    private void login(String url) {
//        System.setProperty("webdriver.chrome.driver", "/Users/wesharecn/Desktop/chromedriver");
        WebDriver driver = new ChromeDriver();
        try {
            driver.get(url);
            WebElement name = new WebDriverWait(driver, 3).until(browser -> browser.findElement(By.id("freename")));
            WebElement pwd = new WebDriverWait(driver, 3).until(browser -> browser.findElement(By.id("freepassword")));
            name.sendKeys("hbyx94@sina.cn");
            pwd.sendKeys("P@ssw0rd.com" + Keys.ENTER);
        } finally {
            ThreadUtil.sleep(5000);
            this.cookies = driver.manage().getCookies();
            driver.quit();
        }
    }
}
